<?php
/**
 * Assign.php
 * 
 * @category   Naneau
 * @package    Naneau_Action_Helper
 * @copyright  Copyright (c) 2007 Maurice Fonk - http://naneau.nl
 * @version    0.2
 */

/**
 * action helper base class
 */
require_once 'Zend/Controller/Action/Helper/Abstract.php';

/**
 * Naneau_Action_Helper_Assign
 * 
 * 
 * Action helper for assigining fields to the action controllers. Has built in
 * option to assign all action helpers as fields.
 *
 * @category   Naneau
 * @package    Naneau_Action_Helper
 * @copyright  Copyright (c) 2007 Maurice Fonk - http://naneau.nl
 */
class Naneau_Action_Helper_Assign extends Zend_Controller_Action_Helper_Abstract {

    /**
     * use underscore?
     * 
     * Using underscores is the proper way of doing it, given the coding
     * standard for the Zend Framework.
     *
     * @var bool
     */
    private $_useUnderscore = true;

    /**
     * assign all helpers in preDispatch?
     *
     * @var bool
     */
    private $_autoFindHelpers = true;

    /**
     * array of plugins
     *
     * @var Zend_Controller_Action_Helper_Abstract[]
     */
    private $_plugins = array();

    /**
     * constructor
     * 
     * @see assign()
     * @param bool $autoFindHelpers automatically assign _all_ action helpers
     * @param bool $useUnderscore use an underscore
     */
    public function __construct($autoFindHelpers = true, $useUnderscore = true) {
        $this->_autoFind = $autoFind;
        $this->_useUnderscore = $useUnderscore;
    }

    /**
     * on every dispatch assign helpers
     * @return void
     */
    public function preDispatch() {
        if ($this->_autoFindHelpers) {
            //find all helpers
            foreach (Zend_Controller_Action_HelperBroker::getExistingHelpers() as $helper) {
                $name = $helper->getName();
                $this->assign($name, $helper);
            }
        }

        $controller = $this->getActionController();
        //current action controller
        foreach($this->_plugins as $name => $plugin) {
            $controller->$name = $plugin;
        }
    }

    /**
     * add an object to be added
     * 
     * @param string $name
     * @param object $obj
     * @return void
     */
    public function assign($name, $obj)
    {
        if ($this->_useUnderscore) {
            $name = '_' .  ltrim($name, '_');
            //remove any possible underscores that are there and add one
        }

        $this->_plugins[$name] = $obj;
        return $this;
        //return self for chaining
    }
}

